package cn.itsource.pet.service.impl;

import cn.itsource.pet.domain.PetType;
import cn.itsource.pet.mapper.PetTypeMapper;
import cn.itsource.pet.service.IPetTypeService;
import cn.itsource.basic.service.impl.BaseImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> getPetTypeTree() {
        //3.没有 - 调用getDeptTreeFormDb()查询数据库 - 把它放到缓存中
        List<PetType> petTypeTreefromDb = getPetTypeTreeFromDb();
        System.out.println(petTypeTreefromDb);
        return petTypeTreefromDb;
    }

    private List<PetType> getPetTypeTreeFromDb() {
        //首先查询出所以department并将其缓存到HashMap中
        Map<Long, PetType> map = new HashMap<>();
        List<PetType> list = petTypeMapper.selectAll();
        //遍历list存入map中
        for (PetType petType : list) {
            map.put(petType.getId(), petType);
        }
        List<PetType> petTypeTree = new ArrayList<>();
        for (PetType petType : list) {
            //如果父节点为空，则直接添加到根节点
            if (petType.getParentId() == null) {
                petTypeTree.add(petType);
            } else {
                //如果父节点不为空，则将父节点的子节点添加到父节点中
                PetType parent = map.get(petType.getParentId());
                if (parent != null) {
                    parent.getChildren().add(petType);
                }
            }
        }
        System.out.println(petTypeTree);
        return petTypeTree;
    }
}
